package com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.lmm.dresswisdom.lmmframe.reactnative.BasePlugin;
import com.lmm.dresswisdom.lmmframe.reactnative.annotation.RNPlugin;
import com.lmm.lcbusiness.lcbusiness.dbmodel.AttrRealm;
import com.lmm.lcbusiness.lcbusiness.dbmodel.CategoryAttr_Relation_Realm;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.ReactNativeActivity;
import com.lmm.lcbusiness.lcbusiness.utils.RealmUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by xmgong on 2017/12/15.
 * 获取商品属性关系
 */
@RNPlugin(method = "getgoodsattrrelation")
public class GetGoodsAttrRelationPlugin extends BasePlugin<ReactNativeActivity> {
    public GetGoodsAttrRelationPlugin(ReactNativeActivity act) {
        super(act);
    }

    @Override
    protected void doAction(Map<String, Object> map, Callback callback) {
        int catid = (int) map.get("catid");
        List<AttrRealm> res = getAttrIdByCatId(catid);
        WritableArray list = Arguments.createArray();
        WritableMap item;
        for (AttrRealm ar : res) {
            item = Arguments.createMap();
            item.putInt("attrId", ar.getAttrId());
            item.putString("attrName", ar.getAttrName());
            item.putInt("sort", ar.getSort());
            item.putInt("isMain", ar.getIsMain());
            item.putInt("isNormal", ar.getIsNormal());
            item.putInt("isMust", ar.getIsMust());
            item.putInt("isDefault", ar.getIsDefault());
            item.putInt("sortNo", ar.getSortNo());
            item.putString("inputType", ar.getInputType());
            item.putInt("dicId", ar.getDicId());
            item.putInt("valueType", ar.getValueType());
            item.putInt("categoryId", ar.getCategoryId());
            list.pushMap(item);
        }
        callback.invoke(list);
    }

    private List<AttrRealm> getAttrIdByCatId(int catid) {
        Realm realm = RealmUtils.getRealm();
        RealmResults<CategoryAttr_Relation_Realm> results = realm.where(CategoryAttr_Relation_Realm.class)
                .equalTo("catId", catid)
                .findAll();
        RealmResults<AttrRealm> attrRealms;
        List<AttrRealm> callback = new ArrayList<>();
        for (CategoryAttr_Relation_Realm crr : results) {
            int attrid = crr.getAttrId();
            attrRealms = realm.where(AttrRealm.class).equalTo("attrId", attrid).findAll();
            callback.addAll(attrRealms);
        }
        return callback;
    }


}
